import { PageContainer } from '@ant-design/pro-components';
import type { RadioChangeEvent } from 'antd';
import { Button, Card, Col, Form, message, Radio, Row, Image, Upload } from 'antd';
import React, { useRef, useState } from 'react';
import BaseModal from '@/components/BaseModal';
import AudioPlayer from './AudioPlayer';
import { baseFormConfig } from '@/components/BaseForm/config';
import { themeButtonStyle } from '../../../config/globalStyle';
import { FileImageOutlined, MinusCircleOutlined } from '@ant-design/icons';
import style from './index.less';
import { history } from 'umi';

const RoleForm = () => {
  const formRef = useRef<any>(null);
  const [roleValue, setRoleValue] = useState('some');
  const [uploadVideoList, setUploadVideoList] = useState<any[]>([]);
  const [uploadImageList, setUploadImageList] = useState<any[]>([]);
  const onFinish = (values: any) => {
    console.log('Success:', values);
  };
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  const onRoleChange = (e: RadioChangeEvent) => {
    console.log('radio checked', e.target.value);
    setRoleValue(e.target.value);
  };
  const props = {
    name: 'file',
    multiple: true,
    showUploadList: false,
    action:
      'http://localhost:8080/api/video/upload                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     ',
    onChange({ file, fileList }: { file: any; fileList: any }) {
      const { status } = file;
      console.log(fileList);
      if (
        status !==
        'uploadin                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                g'
      ) {
        // console.log(file, fileList);
      }
      if (status === 'done') {
        setUploadVideoList(fileList);
        message.success(`${file.name} file uploaded successfully.`);
      } else if (status === 'error') {
        message.error(`${file.name} file upload failed.`);
      }
    },
    onDrop(e) {
      console.log('Dropped files', e.dataTransfer.files);
    },
    beforeUpload: (file: any) => {
      setUploadVideoList([...uploadVideoList, file]);
      return false;
    },
  };
  const imageProps = {
    name: 'file',
    multiple: true,
    showUploadList: false,
    action:
      'http://localhost:8080/api/video/upload                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     ',
    onChange({ file, fileList }: { file: any; fileList: any }) {
      const { status } = file;
      console.log(fileList);
      if (
        status !==
        'uploadin                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                g'
      ) {
        // console.log(file, fileList);
      }
      if (status === 'done') {
        setUploadImageList(fileList);
        message.success(`${file.name} file uploaded successfully.`);
      } else if (status === 'error') {
        message.error(`${file.name} file upload failed.`);
      }
    },
    onDrop(e) {
      console.log('Dropped files', e.dataTransfer.files);
    },
    beforeUpload: (file: any) => {
      setUploadImageList([...uploadImageList, file]);
      return false;
    },
  };
  /** 修改成符合video组件格式的数组 */
  const toTracks = (listParams: any[]) => {
    let list = Array.isArray(listParams) ? listParams : [listParams];
    list = list.map((item, index) => {
      console.log('listitem', item, index);
      return {
        ...item,
        title: item.name,
        artist: 'Wataboi',
        audioSrc: URL.createObjectURL(list[0]),
        image: 'http://p3.music.126.net/tBTNafgjNnTL1KlZMt7lVA==/18885211718935735.jpg',
      };
    });
    return list;
  };
  const toBlobImage = (listParams: any) => {
    let list = Array.isArray(listParams) ? listParams : [listParams];

    list = list.map((item) => {
      return {
        ...item,
        name: item.name,
        src: URL.createObjectURL(list[0]),
      };
    });

    console.log('blob', list);
    return list;
  };
  const onRemove = (file: any) => {
    const index = uploadVideoList.indexOf(file);
    console.log(index);
    const newFileList = uploadVideoList.slice();
    newFileList.splice(index, 1);
    console.log('newFileList', newFileList);
    setUploadVideoList(newFileList);
  };
  const onImageRemove = (file: any) => {
    const index = uploadImageList.indexOf(file);
    const newFileList = uploadImageList.slice();
    newFileList.splice(index, 1);
    setUploadImageList(newFileList);
  };
  const handlePreview = () => {
    const url = URL.createObjectURL(uploadVideoList[0]);
    const audio = new Audio(url);
    console.log('url', url);
    audio.play();
  };

  return (
    <div>
      <Row gutter={24}>
        <Col lg={8} md={8} flex={1}>
          <Card>
            <div
              style={{
                width: '100px',
                height: '100px',
                backgroundSize: 'cover',
                backgroundImage: `url(${toBlobImage(uploadImageList)[0]?.src})`,
                // https://img.js.design/assets/img/6361e55cf0632576635fffe0.png#2af78920443a58cf03a5498b0b08afdf
              }}
            >
              hello world
              {uploadImageList[0]?.src} {JSON.stringify(toBlobImage(uploadImageList))}
            </div>
            {/* <img src={uploadImageList[0]?.src ?? null} alt="" /> */}
            {/* <img src={'blob:http://localhost:8000/bb5283f3-bd53-4254-acf8-87a793a335d1'} alt="" /> */}
          </Card>
        </Col>
        <Col lg={16} md={16}>
          <Form
            {...baseFormConfig}
            ref={formRef}
            name="basic"
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
          >
            <Form.Item
              label="音乐"
              name="title"
              rules={[{ required: true, message: '请上传音乐!' }]}
            >
              <Upload {...props}>
                <Button type="primary">上传音乐</Button>
              </Upload>
              <div
                style={{
                  width: '500px',
                }}
              >
                {uploadVideoList.map((file, index) => {
                  return (
                    <li
                      style={{
                        display: 'flex',
                        flexDirection: 'row',
                        marginTop: '10px',
                      }}
                      key={file.uid}
                    >
                      <AudioPlayer tracks={toTracks(uploadVideoList[index])} />
                      <button
                        onClick={() => onRemove(file)}
                        style={{
                          display: 'flex',
                          top: '0px',
                        }}
                      >
                        <MinusCircleOutlined
                          style={{
                            backgroundColor: 'red',
                            color: 'white',
                            borderRadius: '50%',
                          }}
                        />
                      </button>
                    </li>
                  );
                })}
              </div>
            </Form.Item>
            <Form.Item
              label="是否翻页"
              name="role"
              rules={[{ required: true, message: '请选择视是否翻页' }]}
              style={{
                marginTop: '30px',
                marginBottom: '30px',
              }}
            >
              <Radio.Group onChange={onRoleChange} defaultValue={roleValue} value={roleValue}>
                <Radio value="all">是</Radio>
                <Radio value="some">否</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              label="背景上传"
              name="background"
              rules={[{ required: true, message: '请上传背景' }]}
            >
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'row',
                  width: '500px',
                }}
              >
                <Upload
                  {...imageProps}
                  action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                  listType="picture"
                  // defaultFileList={[...fileList]}
                >
                  <div className={style.imageUpload}>
                    <FileImageOutlined
                      style={{
                        color: 'rgba(21, 192, 230, 1)',
                        backgroundColor: 'rgba(21, 192, 230, 0.1)',
                      }}
                    />
                  </div>
                </Upload>
                <div
                  style={{
                    display: 'flex',
                    flexDirection: 'row',
                  }}
                  className={style.imageParent}
                >
                  {uploadImageList.map((item) => {
                    return (
                      <div
                        key={item.name}
                        style={{
                          display: 'flex',
                          flexDirection: 'row',
                        }}
                      >
                        <Image width={100} src={toBlobImage(item)[0].src} />
                        <button
                          onClick={() => onImageRemove(item)}
                          style={{
                            display: 'flex',
                            top: '0px',
                          }}
                        >
                          <MinusCircleOutlined
                            style={{
                              backgroundColor: 'red',
                              color: 'white',
                              borderRadius: '50%',
                            }}
                          />
                        </button>
                      </div>
                    );
                  })}
                </div>
              </div>
            </Form.Item>
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
              }}
            >
              <Button key="cancel" className="cancel-button">
                取消
              </Button>
              <Button key="submit" type="primary" className="cancel-button">
                确定
              </Button>
            </div>
          </Form>
        </Col>
      </Row>
    </div>
  );
};

const EditModal = (props: any) => {
  const baseModalConfig = {
    ...props,
    title: '编辑通知书',
    width: '850px',
    footer: false,
    ModalChildren: RoleForm,
  };
  return (
    <div>
      <BaseModal {...baseModalConfig} />
    </div>
  );
};
const Edit: React.FC = () => {
  const [open, setOpen] = useState(false);
  const EditModalConfig = {
    handleOpen: () => setOpen(true),
    handleClose: () => setOpen(false),
    isModalOpen: open,
  };
  // const tracks = ['http://localhost:8080/1679640275779-zhijianqiu-2648569280.mp3']
  const tracks = [
    {
      title: 'Cali',
      artist: 'Wataboi',
      audioSrc: 'http://localhost:8080/1679640275779-zhijianqiu-2648569280.mp3',
      image: 'http://p3.music.126.net/tBTNafgjNnTL1KlZMt7lVA==/18885211718935735.jpg',
      // color: "#00aeb0"
    },
  ];
  return (
    <PageContainer>
      <Card>
        <Button
          onClick={() => history.push('/notificationSettings/template')}
          style={themeButtonStyle}
        >
          编辑通知书
        </Button>
        {/* <AudioPlayer tracks={tracks} /> 测试用  */}
        {/* https://juejin.cn/post/6998462438781747236#comment */}
      </Card>
      <EditModal {...EditModalConfig} />
    </PageContainer>
  );
};
export default Edit;
